<!-- 
  videojs视频播放
  用法：
    <f7-row ref="videoPlayer" style="left:0; margin-top:44px;width:100%;z-index:1000;">
      <f7-video-player
        :datakey="dataKey"
        :title="videoTitle"
        :sources="playerSources"
        @onPlayerReadied="onPlayerReadied"
        @onPlayerTimeupdate="onPlayerTimeupdate"
        @onPlayerEnded="onPlayerEnded()"
      ></f7-video-player>
    </f7-row>

  参数：
    sources：表示视频的地址，取值参考：
          playerSources: [
            {
              type: "video/mp4",
              src: "http://vjs.zencdn.net/v/oceans.mp4"
            }
          ],
 -->
<template>
  <f7-videojs
    style="width: 100%;"
    class="video-player vjs-custom-skin"
    ref="videoPlayer"
    :playsinline="false"
    :options="playerOptions"
    @timeupdate="onPlayerTimeupdate"
    @ready="onPlayerReadied"
    @ended="onPlayerEnded"
  ></f7-videojs>
</template>
<script>
import Util from "../framework/util";
export default {
  props: {
    options: {
      type: Object
    },
    sources: {
      type: Array
    },
    datakey: {
      type: String
    },
    title: {
      type: String
    }
  },
  computed: {
    playerOptions() {
      return this.$util.extend(
        {
          //playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
          autoplay: false, //如果true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 导致视频一结束就重新开始。
          preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: "zh-CN",
          aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [
            // {
            //   type: "video/mp4",
            //   src: '' //你的m3u8地址（必填）
            // }
            // {
            //   type: "application/x-mpegURL",
            //   src: "http://cstv.live.wscdns.com/live/xiamen4/playlist.m3u8" //你的m3u8地址（必填）
            // }
          ],
          poster: "/static/img/poster.jpg", //你的封面地址
          //width: document.documentElement.clientWidth,
          notSupportedMessage: "此视频暂无法播放，请稍后再试" //允许覆盖Video.js无法播放媒体源时显示的默认信息。
          //  controlBar: {
          //   timeDivider: true,
          //   durationDisplay: true,
          //   remainingTimeDisplay: false,
          //   fullscreenToggle: true //全屏按钮
          //  }
        },
        this.options || {},
        {
          sources:
            (this.options &&
            this.options.sources &&
            this.options.sources.length > 0
              ? this.options.sources
              : this.sources) || []
        }
      );
    }
  },
  methods: {
    onPlayerTimeupdate(player) {
      this.$emit("onPlayerTimeupdate", player);
      if (player.currentTime() > 1) {
        let url = player.currentSource().src;
        this.$framework.db.videoLog.get(url, v => {
          let u = {
            url: url,
            userId: this.$f7.data.currentUser.userId,
            currentTime: player.currentTime(),
            logTime: new Date(),
            datakey: this.datakey,
            progress: player.currentTime() / player.duration(),
            isReport: false
          };
          if (v) {
            this.$framework.db.videoLog.update(url, u);
          } else {
            this.$framework.db.videoLog.put(
              this.$framework.util.extend(
                {
                  isNotRecord: false,
                  lastTime: 0.0
                },
                u
              )
            );
          }
        });
        
        let userId = this.$f7.data.currentUser.userId;

        this.$framework.db.videoPlayRecord.filter((item) => {
          return item.url == url && item.userId == userId && item.progress != 1;
        }).first((v) => {
          let u = {
            url: url,
            userId: userId,
            currentTime: player.currentTime(),
            startDate: new Date(),
            datakey: this.datakey,
            progress: player.currentTime() / player.duration(),
            title: this.title,
            isReport: false
          };
          if (v) {
            if (u.progress >= v.progress) {
              // 大于才更新
              this.$framework.db.videoPlayRecord.update(v.key, u);
            }
          } else {
            // 如果一开始视频进度为1，说明上次看完了
            if (u.progress != 1) {
              this.$framework.db.videoPlayRecord.put(
                this.$framework.util.extend(
                  {
                    key: this.$framework.util.random(32),
                  },
                  u
                )
              );
            }
          }
        });
      }
    },
    onPlayerReadied(player) {
      this.$emit("onPlayerReadied", "");
      player.on("fullscreenchange", function(a) {
        if (window.plus) {
          if (player.isFullscreen_) {
            //横屏
            plus.screen.lockOrientation("landscape");
          } else {
            //竖屏
            plus.screen.lockOrientation("portrait");
          }
        }
      });
      if (player.currentTime() <= 0) {
        player.currentTime(1);
        this.fillCurrentTime(player);
      }
    },
    onPlayerEnded(player) {
      // 触发事件
      this.$emit("onPlayerEnded", "");
    }, 
    fillCurrentTime(player) {
      let src = player.currentSource().src;
      if (src) {
        this.$framework.db.videoLog.get(
          { url: src, userId: this.$f7.data.currentUser.userId },
          log => {
            if (log && log.currentTime > player.currentTime()) {
              player.currentTime(log.currentTime);
            }
            player.poster("");
          }
        );
      }
    }
  }
};
</script>
